package org.jeecg.modules.yfRepair.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.JsonUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.yfRepair.entity.HqYfRepair;
import org.jeecg.modules.yfRepair.entity.HqYfRepairPiece;
import org.jeecg.modules.yfRepair.mapper.HqYfRepairPieceMapper;
import org.jeecg.modules.yfRepair.mapper.HqYfRepairMapper;
import org.jeecg.modules.yfRepair.service.IHqYfRepairService;
import org.jeecg.modules.yfRepair.vo.HqYfRepairPage;
import org.jeecg.modules.zhaojd.entity.HqZhaojd;
import org.jeecg.modules.zhaojd.entity.HqZhaojdChif;
import org.jeecg.modules.zhaojd.entity.HqZhaojdDetail;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Collection;
import java.util.Map;

/**
 * @Description: 营房报修
 * @Author: jeecg-boot
 * @Date:   2020-06-13
 * @Version: V1.0
 */
@Service
public class HqYfRepairServiceImpl extends ServiceImpl<HqYfRepairMapper, HqYfRepair> implements IHqYfRepairService {

	@Autowired
	private HqYfRepairMapper hqYfRepairMapper;
	@Autowired
	private HqYfRepairPieceMapper hqYfRepairPieceMapper;

	@Autowired
	private RuntimeService runtimeservice;
	@Autowired
	private TaskService taskService;
	@Autowired
	private RepositoryService repositoryService;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private IdentityService identityservice;
	
	@Override
	@Transactional
	public void saveMain(HqYfRepair hqYfRepair, List<HqYfRepairPiece> hqYfRepairPieceList) {
		hqYfRepairMapper.insert(hqYfRepair);
		if(hqYfRepairPieceList!=null && hqYfRepairPieceList.size()>0) {
			for(HqYfRepairPiece entity:hqYfRepairPieceList) {
				//外键设置
				entity.setZhubId(hqYfRepair.getId());
				hqYfRepairPieceMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void updateMain(HqYfRepair hqYfRepair,List<HqYfRepairPiece> hqYfRepairPieceList) {
		hqYfRepairMapper.updateById(hqYfRepair);
		
		//1.先删除子表数据
		hqYfRepairPieceMapper.deleteByMainId(hqYfRepair.getId());
		
		//2.子表数据重新插入
		if(hqYfRepairPieceList!=null && hqYfRepairPieceList.size()>0) {
			for(HqYfRepairPiece entity:hqYfRepairPieceList) {
				//外键设置
				entity.setZhubId(hqYfRepair.getId());
				hqYfRepairPieceMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void delMain(String id) {
		hqYfRepairPieceMapper.deleteByMainId(id);
		hqYfRepairMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			hqYfRepairPieceMapper.deleteByMainId(id.toString());
			hqYfRepairMapper.deleteById(id);
		}
	}

	@Override
	public void startFlow(HqYfRepair hqYfRepair, LoginUser loginUser) {
		// 报修流程审批人固定
//		List<SysUser> userList = sysUserService.queryByPost(loginUser.getOrgCode(),"shenpiren");
//		if(CollectionUtils.isEmpty(userList)) {
//			throw new RuntimeException("当前部门审批人为空");
//		}

		String businesskey = "" + hqYfRepair.getId();
		identityservice.setAuthenticatedUserId(hqYfRepair.getCreateBy());

		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("applyUser", loginUser.getUsername());
//		variables.put("auditUser",userList.get(0).getUsername());
		Model modelData = repositoryService.getModel("405001");
		ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(modelData.getDeploymentId()).singleResult();

		ProcessInstance instance=runtimeservice.startProcessInstanceById(processDefinition.getId(),businesskey,variables);
		String instanceid=instance.getId();
		Task task = taskService.createTaskQuery().processInstanceId(instance.getId()).taskAssignee(loginUser.getUsername()).singleResult();

		hqYfRepair.setProcessInstanceId(instanceid);
		hqYfRepair.setWeixzt("1");
		hqYfRepair.setTaskId(task.getId());
		this.baseMapper.updateById(hqYfRepair);

		taskService.complete(task.getId(), variables);
	}

	@Override
	public IPage<HqYfRepair> taskList(String userId, Integer pageNo, Integer pageSize) {
		return null;
	}

	@Override
	public void complateTask(String taskId, String processInstanceId, Integer status, String memo, String weixgs, String weixry) {
		Map map = new HashMap() {{
			put("status", status);

			// 指派维修公司
			if(weixgs != null)
				put("weixgspd", weixgs);

			// 指派维修人员
			if(weixry != null)
				put("weixry", weixry);
		}};

		if(memo != null && !StringUtils.isBlank(memo)) {
			map.put("memo", memo);
			taskService.addComment(taskId, processInstanceId, JsonUtils.toJsonString(map));
		}

		taskService.complete(taskId, map);
	}

	@Override
	public void applyAgain(HqYfRepairPage hqYfRepairPage, LoginUser user) {
		HqYfRepair hqZhaojd = new HqYfRepair();
		BeanUtils.copyProperties(hqYfRepairPage, hqZhaojd);

		Task task = taskService.createTaskQuery().processInstanceId(hqZhaojd.getProcessInstanceId()).taskAssignee(user.getUsername()).singleResult();
		hqZhaojd.setTaskId(task.getId());
		this.baseMapper.updateById(hqZhaojd);

		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("status",null);
		taskService.complete(task.getId(),variables);
	}

	@Override
	public IPage<HqYfRepair> myApplyList(Page<HqYfRepair> page, @Param("user")LoginUser user, @Param("hqYfRepair")HqYfRepair hqYfRepair) {
		return this.baseMapper.myApplyList(page, user, hqYfRepair);
	}

	@Override
	public IPage<HqYfRepair> myTodoTasks(Page<HqYfRepair> page, @Param("user")LoginUser user, @Param("hqYfRepair")HqYfRepair hqYfRepair) {
		return this.baseMapper.myTodoTasks(page,user,hqYfRepair);
	}

	@Override
	public IPage<HqYfRepair> myDoneTasks(Page<HqYfRepair> page, @Param("user")LoginUser user, @Param("hqYfRepair")HqYfRepair hqYfRepair) {
		return this.baseMapper.myDoneTasks(page,user,hqYfRepair);
	}


}
